package com.blogspot.ddmytrenko.getfile.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.blogspot.ddmytrenko.getfile.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class TestUI extends Activity {
	
	public static final String TAG = "GF_UI_T";
	
	public static final int DOWNLOADING_BUFFER_SIZE = 1024;
	public static final String HTTP_GET_REQUEST = "GET";
	
	EditText etLink;
	EditText etFile;
	Button btnDload;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_ui);
		initUI();
	}
	
	private void initUI() {
		etLink = (EditText) findViewById(R.id.et_link);
		etFile = (EditText) findViewById(R.id.et_filename);
		btnDload = (Button) findViewById(R.id.b_download);
		btnDload.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				String link = etLink.getText().toString();
				if((link==null) || ("".equals(link))) {
					Toast.makeText(TestUI.this, "Nothing to download.", Toast.LENGTH_LONG).show();
					etLink.requestFocus();
				}
				else {
					String fileName = etFile.getText().toString();
					if((fileName==null) || ("".equals(fileName)))
						fileName = link.substring(link.lastIndexOf('/')+1, link.length());
					Log.i(TestUI.TAG, "link="+link+" file="+fileName);
					new DownloadTask().execute(new String[] {link, fileName});
				}
			}
		});
	}
	
	private class DownloadTask extends AsyncTask<String, Integer, Integer> {
		
		ProgressDialog dialog;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(TestUI.this);
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setTitle("GetFile");
			dialog.setMessage("Downloading file...");
			dialog.setCancelable(false);
			dialog.setProgress(0);
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(String... params) {
			try {
				URL url = new URL(params[0]);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				
				connection.setRequestMethod(TestUI.HTTP_GET_REQUEST);
				connection.setDoOutput(true);
				connection.connect();
				
				File sdCardRoot = Environment.getExternalStorageDirectory();
				File file = new File(sdCardRoot, params[1]);
				
				FileOutputStream fos = new FileOutputStream(file);
				InputStream is = connection.getInputStream();
				
				int totalSize = connection.getContentLength();
				int downloadedSize = 0;
				
				byte[] buffer = new byte [TestUI.DOWNLOADING_BUFFER_SIZE];
				int bufferLen = 0;
				
				while((bufferLen = is.read(buffer)) > 0) {
					fos.write(buffer, 0, bufferLen);
					downloadedSize += bufferLen;
					//Log.i(TestUI.TAG, "ds="+downloadedSize+" ts="+totalSize);
					publishProgress(new Integer[] {downloadedSize, totalSize});
				}
				fos.close();
			} catch(MalformedURLException e) {
				Log.e(TestUI.TAG, "E: Malformed URL! " + e.getLocalizedMessage());
				return 1;
			} catch(IOException e) {
				Log.e(TestUI.TAG, "E: I/O error! " + e.getLocalizedMessage());
				return 2;
			}
			return 0;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			dialog.setMax(values[1]);
			dialog.setProgress(values[0]);
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			dialog.dismiss();
			switch (result) {
			case 0:
				Toast.makeText(TestUI.this, "Downloading finished", Toast.LENGTH_LONG).show();
				break;
			case 1:
				Toast.makeText(TestUI.this, "E: Malformed URL!", Toast.LENGTH_LONG).show();
				break;
			case 2:
				Toast.makeText(TestUI.this, "E: I/O error!", Toast.LENGTH_LONG).show();
				break;
			default:
				break;
			}
		}
	}

}
